const config = require('_/config');
const jwt = require('jsonwebtoken');

// 生成token
exports.createToken = async (userInfo = {}) => {
  const token = jwt.sign(userInfo, config.secretKey, {
    expiresIn: '10h'
  });
  return token;
};

// 验证token
exports.verifyToken = () => {
  return async(ctx, next) => {
    if(config.noTokenUrl.includes(ctx.request.path)) {
      await next();
    }else {
      let token = ctx.request.headers['authorization'];
      if(token) {
        await jwt.verify(token, config.secretKey, async (err, info) => {
          if(err) {
            ctx.session.token = null;
            ctx.session.userInfo = null;
            ctx.fail({status: 401, message: '令牌过期'})
          }else {
            if(ctx.session.token) {
              await next();
            }else {
              ctx.fail({status: 401, message: '令牌已退出'})
            }
          }
        })
      }else {
        ctx.fail({status: 401, message: '请求没有令牌'});
      }
    }
  }
};



